import React, { useEffect, useState } from 'react';
import { UserAuth } from '../../utils/hooks';
import NotAuth from '../../components/NotAuth';
import {
  Button,
  Layout,
  message,
  Modal,
  Drawer,
  Table,
  Row,
  InputNumber,
  Col,
  Input,
  Form,
} from 'antd';
import { Content, Header } from 'antd/lib/layout/layout';
import { PlusOutlined } from '@ant-design/icons';
import axios from 'axios';
import Config from '../../Config';
const DataDict = () => {
  const [DictData, SetDict] = useState([]);
  const [loading, SetLoading] = useState(false);
  const [drawVis, SetDraw] = useState(false);
  const [dictModal, SetdictModal] = useState(false);
  const [detailModal, SetDetailModal] = useState(false);
  const [detailData, SetDetail] = useState([]);
  const [curDict, SetCurDict] = useState(-1);
  const [curDetail, SetcurDetail] = useState(-1);
  const [DictEdit, SetDictEdit] = useState(0);
  const [detailEdit, SetDetailEdit] = useState(0);
  const [dictForm] = Form.useForm();
  const [detailForm] = Form.useForm();
  const [dictRefresh, SetdictRefresh] = useState(false);
  useEffect(() => {
    SetLoading(true);
    axios
      .get(Config.baseURL + '/dict/getAllDict')
      .then(res => {
        if (res.data.code == 1) {
          let data = res.data.data;
          console.log(data);
          SetDict(data);
          SetLoading(false);
        } else if (res.data.code >= 10000) {
          message.error('获取失败 ' + res.data.message, 2);
          SetLoading(false);
        }
      })
      .catch(err => {
        message.error('后台出错 ' + err, 2);
        SetLoading(false);
      });
  }, [dictRefresh]);
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '字典名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '字典编号',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '描述',
      dataIndex: 'descript',
      key: 'descript',
    },
    {
      title: '操作',
      render: (_, value) => {
        return (
          <>
            <a
              onClick={() => {
                SetdictModal(true);
                dictForm.setFieldsValue({
                  name: value.name,
                  descript: value.descript,
                  code: value.code,
                });
                SetDictEdit(1);
                SetCurDict(value.id);
              }}
            >
              编辑
            </a>
            <a
              style={{ marginLeft: '5px' }}
              onClick={() => {
                axios
                  .get(Config.baseURL + '/dict/getDictDetail/' + value.id)
                  .then(res => {
                    if (res.data.code == 1) {
                      let data = res.data.data;
                      SetDetail(data);
                      SetCurDict(value.id);
                      SetDraw(true);
                    } else if (res.data.code >= 10000) {
                      message.error('获取失败 ' + res.data.message, 2);
                    }
                  })
                  .catch(err => {
                    message.error('后台出错 ' + err, 2);
                  });
              }}
            >
              字典管理
            </a>
            <a
              style={{ marginLeft: '5px' }}
              onClick={() => {
                axios
                  .get(Config.baseURL + '/dict/delete/' + value.id)
                  .then(res => {
                    if (res.data.code == 1) {
                      message.success('删除成功');
                      SetdictRefresh(!dictRefresh);
                    } else if (res.data.code >= 10000) {
                      message.error('获取失败 ' + res.data.message, 2);
                    }
                  })
                  .catch(err => {
                    message.error('后台出错 ' + err, 2);
                  });
              }}
            >
              删除
            </a>
          </>
        );
      },
    },
  ];
  const columns1 = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '数据值',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '操作',
      render: (_, value) => {
        return (
          <>
            <a
              onClick={() => {
                SetDetailModal(true);
                detailForm.setFieldsValue({
                  name: value.name,
                  code: value.code,
                  sort: value.sort,
                });
                SetDetailEdit(1);
                SetcurDetail(value.id);
              }}
            >
              编辑
            </a>
            <a
              style={{ marginLeft: '5px' }}
              onClick={() => {
                axios
                  .get(Config.baseURL + '/dict/deleteDetail/' + value.id)
                  .then(res => {
                    if (res.data.code == 1) {
                      message.success('操作成功', 2);
                      axios
                        .get(Config.baseURL + '/dict/getDictDetail/' + curDict)
                        .then(res => {
                          if (res.data.code == 1) {
                            let data = res.data.data;
                            SetDetail(data);
                          } else if (res.data.code >= 10000) {
                            message.error('获取失败 ' + res.data.message, 2);
                          }
                        })
                        .catch(err => {
                          message.error('后台出错 ' + err, 2);
                        });
                      SetDetailModal(false);
                    } else if (res.data.code >= 10000) {
                      message.error('获取失败 ' + res.data.message, 2);
                      SetDetailModal(false);
                    }
                  })
                  .catch(err => {
                    message.error('后台出错 ' + err, 2);
                    SetDetailModal(false);
                  });
              }}
            >
              删除
            </a>
          </>
        );
      },
    },
  ];
  const layout = {
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 16,
    },
  };
  const onClose = () => {
    SetDraw(false);
  };
  const DictModalOk = () => {
    let data = dictForm.getFieldsValue();
    console.log(dictForm.getFieldsValue());
    axios
      .post(Config.baseURL + '/dict/ChangeDict', {
        type: DictEdit,
        ...data,
        id: curDict,
      })
      .then(res => {
        if (res.data.code == 1) {
          message.success('操作成功', 2);
          SetdictRefresh(!dictRefresh);
          SetdictModal(false);
        } else if (res.data.code >= 10000) {
          message.error('获取失败 ' + res.data.message, 2);
          SetdictModal(false);
        }
      })
      .catch(err => {
        message.error('后台出错 ' + err, 2);
        SetdictModal(false);
      });
  };
  const DetailModalOk = () => {
    let data = detailForm.getFieldsValue();
    axios
      .post(Config.baseURL + '/dict/ChangeDetail', {
        type: detailEdit,
        ...data,
        id: curDetail,
        dictId: curDict,
      })
      .then(res => {
        if (res.data.code == 1) {
          message.success('操作成功', 2);
          axios
            .get(Config.baseURL + '/dict/getDictDetail/' + curDict)
            .then(res => {
              if (res.data.code == 1) {
                let data = res.data.data;
                SetDetailModal(false);
                SetDetail(data);
              } else if (res.data.code >= 10000) {
                message.error('获取失败 ' + res.data.message, 2);
              }
            })
            .catch(err => {
              message.error('后台出错 ' + err, 2);
            });
          SetDetailModal(false);
        } else if (res.data.code >= 10000) {
          message.error('获取失败 ' + res.data.message, 2);
          SetDetailModal(false);
        }
      })
      .catch(err => {
        message.error('后台出错 ' + err, 2);
        SetDetailModal(false);
      });
  };
  return (
    <>
      <Layout>
        <Content style={{ padding: '10px 20px', backgroundColor: 'white', height: '80vh' }}>
          <Row>
            <Button
              type="primary"
              size="large"
              onClick={() => {
                SetdictModal(true);
                SetCurDict(-1);
                SetDictEdit(0);
                dictForm.setFieldsValue({
                  name: '',
                  code: '',
                  descript: '',
                });
              }}
            >
              <PlusOutlined />
              添加
            </Button>
          </Row>
          <Row style={{ width: '100%', marginTop: '20px' }}>
            <Table style={{ width: '100%' }} dataSource={DictData} columns={columns}></Table>
          </Row>
        </Content>
      </Layout>
      <Drawer width={600} title="字典列表" placement="right" onClose={onClose} visible={drawVis}>
        <Row>
          <Button
            type="primary"
            size="large"
            onClick={() => {
              SetDetailModal(true);
              SetcurDetail(-1);
              SetDetailEdit(0);
              detailForm.setFieldsValue({
                name: '',
                code: '',
                descript: '',
                sort: 1,
              });
            }}
          >
            添加
          </Button>
        </Row>
        <Row style={{ width: '100%', marginTop: '20px' }}>
          <Table style={{ width: '100%' }} dataSource={detailData} columns={columns1}></Table>
        </Row>
      </Drawer>
      <Modal
        visible={dictModal}
        title="字典编辑"
        okText="修改"
        cancelText="取消"
        onCancel={() => {
          SetdictModal(false);
        }}
        onOk={DictModalOk}
        width={600}
      >
        <Form {...layout} form={dictForm}>
          <Form.Item
            name="name"
            label="字典名称"
            rules={[
              {
                required: true,
                message: '请输入字典名称!',
              },
            ]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            name="code"
            label="字典编号"
            rules={[
              {
                pattern: /^[a-z0-9A-Z_-]{1,16}$/,
                message: '请输入正确格式',
              },
              {
                required: true,
                message: '请输入字典编号!',
              },
            ]}
          >
            <Input disabled={DictEdit == 1}></Input>
          </Form.Item>

          <Form.Item name="descript" label="字典描述">
            <Input></Input>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="字典项编辑"
        okText="修改"
        cancelText="取消"
        onCancel={() => {
          SetDetailModal(false);
        }}
        onOk={DetailModalOk}
        width={600}
        visible={detailModal}
      >
        <Form {...layout} form={detailForm}>
          <Form.Item
            name="name"
            label="字典项名称"
            rules={[
              {
                required: true,
                message: '请输入字典项名称!',
              },
            ]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            name="code"
            label="数据值"
            rules={[
              {
                pattern: /^[a-z0-9A-Z_-]{1,16}$/,
                message: '请输入正确格式',
              },
              {
                required: true,
                message: '请输入数据值!',
              },
            ]}
          >
            <Input disabled={DictEdit == 1}></Input>
          </Form.Item>
          <Form.Item name="descript" label="描述">
            <Input></Input>
          </Form.Item>
          <Form.Item name="sort" label="排序值">
            <InputNumber defaultValue={1}></InputNumber>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default () => {
  const { authority } = UserAuth('DataDict');
  return <>{authority ? <DataDict /> : <NotAuth />}</>;
};
